<template>
  <div>
    <label for="phoneNumber">输入电话号码:</label>
    <input v-model="inputPhoneNumber" @input="onPhoneNumberInput" id="phoneNumber" type="tel" />

    <ul v-if="detectedCountryCode">
      <li> 检测到的国家/地区代码: {{ detectedCountryCode }}</li>
      <li>国际格式的号码: {{ formattedNumber }}</li>
      <li>国内格式的号码: {{ formattedLocalNumber }}</li>
      <li> E.164: {{ formattedE164Number }}</li>
      <li> RFC3966 Format: {{ rfc3966Format  }}</li>
    </ul>
    <p v-else>No valid country code detected.</p>
  </div>
</template>

<script>
import { PhoneNumberUtil, PhoneNumberFormat } from 'google-libphonenumber';

export default {
  data() {
    return {
      inputPhoneNumber: '',
      detectedCountryCode: '',
      formattedNumber: '',
      formattedLocalNumber: '',
      formattedE164Number: '',
      rfc3966Format : '',
    };
  },
  methods: {
    onPhoneNumberInput() {
      // Use libphonenumber to parse the phone number
      const phoneUtil = PhoneNumberUtil.getInstance();
      try {
        const phoneNumber = phoneUtil.parseAndKeepRawInput(this.inputPhoneNumber, 'ZZ');
        if (phoneUtil.isValidNumber(phoneNumber)) {
          // Get the country code
          this.detectedCountryCode = `+${phoneNumber.getCountryCode()}`;
          this.formattedNumber = phoneUtil.format(phoneNumber, PhoneNumberFormat.INTERNATIONAL);
          this.formattedLocalNumber = phoneUtil.format(phoneNumber, PhoneNumberFormat.NATIONAL);
          this.formattedE164Number = phoneUtil.format(phoneNumber, PhoneNumberFormat.E164);
          this.rfc3966Format  = phoneUtil.format(phoneNumber, PhoneNumberFormat.RFC3966);

        } else {
          this.detectedCountryCode = '';
        }
      } catch (error) {
        // Handle incomplete phone numbers or other parsing errors
        if (error.message.includes('Invalid country calling code') && this.inputPhoneNumber.trim() === '+') {
          // Handle incomplete country code (e.g., just '+')
          this.detectedCountryCode = '';
        } else {
          console.error('Error parsing phone number:', error);
          this.detectedCountryCode = '';
        }
      }
    },
  },
};
</script>
